﻿using System.Collections.Concurrent;

namespace CS.Beehive
{
    /// <summary>
    /// 数据片池
    /// </summary>
    public class DatagramPool
    {
        private readonly ConcurrentStack<Datagram> _pool;

        private readonly int _bufferSize;

        public DatagramPool(int poolSize, int bufferSize)
        {
            _bufferSize = bufferSize;
            for (int i = 0; i < poolSize; i++)
            {
                _pool.Push(CreateItem());
            }
        }

        /// <summary>
        /// 池中剩余数量
        /// </summary>
        public int Count
        {
            get { return _pool.Count; }
        }

        /// <summary>
        /// 弹出一个
        /// </summary>
        /// <returns></returns>
        public Datagram Pop()
        {
            Datagram item;
            if (!_pool.TryPop(out item))
            {
                item = CreateItem();
            }
            return item;
        }
        /// <summary>
        /// 压回
        /// </summary>
        /// <param name="item"></param>
        public void Push(Datagram item)
        {
            item.Reset();
            _pool.Push(item);
        }


        private Datagram CreateItem()
        {
            return new Datagram(_bufferSize);
        }





    }
}